using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;

namespace JGSY.CMS.LowCode.Platform.Application.Services
{
    /// <summary>
    /// 风险评估应用服务实现
    /// </summary>
    public class RiskAssessmentAppService : IRiskAssessmentAppService
    {
        private readonly ILogger<RiskAssessmentAppService> _logger;

        public RiskAssessmentAppService(ILogger<RiskAssessmentAppService> logger)
        {
            _logger = logger;
        }

        public async Task<RiskAssessmentResultDto> CalculateRiskScoreAsync(RiskAssessmentContextDto context)
        {
            try
            {
                _logger.LogInformation("Starting risk assessment for user {UserId}", context.UserId);

                // 模拟风险评估计算
                await Task.Delay(10);

                // 创建风险因子分析
                var factors = new RiskFactorsDto
                {
                    DeviceTrust = CalculateDeviceTrust(context),
                    LocationConsistency = CalculateLocationConsistency(context),
                    TimePattern = CalculateTimePattern(context),
                    LoginFrequency = CalculateLoginFrequency(context),
                    BehaviorPattern = CalculateBehaviorPattern(context)
                };

                // 计算综合风险评分
                var score = factors.DeviceTrust * 0.25 +
                           factors.LocationConsistency * 0.2 +
                           factors.TimePattern * 0.15 +
                           factors.LoginFrequency * 0.2 +
                           factors.BehaviorPattern * 0.2;

                // 确定风险等级
                var level = GetRiskLevel(score);

                // 生成安全建议
                var recommendations = GenerateRecommendations(factors, level);

                var result = new RiskAssessmentResultDto
                {
                    Score = Math.Round(score, 2),
                    Level = level,
                    Factors = factors,
                    Recommendations = recommendations
                };

                _logger.LogInformation("Risk assessment completed for user {UserId}, Score: {Score}, Level: {Level}", 
                    context.UserId, result.Score, result.Level);

                return result;
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error calculating risk score for user {UserId}", context.UserId);
                throw;
            }
        }

        private double CalculateDeviceTrust(RiskAssessmentContextDto context)
        {
            // 简单的设备信任度计算
            if (string.IsNullOrEmpty(context.DeviceFingerprint))
                return 0.3;

            // 模拟已知设备检查
            var knownDeviceHashes = new[] { "known_device_1", "known_device_2", "trusted_device" };
            if (knownDeviceHashes.Contains(context.DeviceFingerprint))
                return 0.9;

            return 0.5;
        }

        private double CalculateLocationConsistency(RiskAssessmentContextDto context)
        {
            // 简单的位置一致性计算
            if (context.Location == null)
                return 0.5;

            // 模拟常用位置检查
            var commonLocations = new[] { "北京", "上海", "深圳" };
            if (commonLocations.Contains(context.Location.City))
                return 0.8;

            return 0.4;
        }

        private double CalculateTimePattern(RiskAssessmentContextDto context)
        {
            // 简单的时间模式分析
            var hour = context.Timestamp.Hour;
            
            // 正常工作时间 (8-18点) 风险较低
            if (hour >= 8 && hour <= 18)
                return 0.8;

            // 深夜时间 (2-6点) 风险较高
            if (hour >= 2 && hour <= 6)
                return 0.2;

            return 0.6;
        }

        private double CalculateLoginFrequency(RiskAssessmentContextDto context)
        {
            // 简单的登录频率分析 - 在实际实现中需要查询数据库
            // 这里返回固定值作为示例
            return 0.7;
        }

        private double CalculateBehaviorPattern(RiskAssessmentContextDto context)
        {
            // 简单的行为模式分析
            if (string.IsNullOrEmpty(context.UserAgent))
                return 0.4;

            // 检查是否为常见的浏览器用户代理
            var commonUserAgents = new[] { "Chrome", "Firefox", "Safari", "Edge" };
            var isCommonBrowser = commonUserAgents.Any(ua => context.UserAgent.Contains(ua));

            return isCommonBrowser ? 0.7 : 0.3;
        }

        private string GetRiskLevel(double score)
        {
            if (score <= 0.3) return "LOW";
            if (score <= 0.6) return "MEDIUM";
            if (score <= 0.8) return "HIGH";
            return "CRITICAL";
        }

        private List<string> GenerateRecommendations(RiskFactorsDto factors, string level)
        {
            var recommendations = new List<string>();

            if (level == "CRITICAL" || level == "HIGH")
            {
                recommendations.Add("建议立即启用两步验证");
                recommendations.Add("建议人工审核此次登录");
            }

            if (factors.DeviceTrust < 0.3)
                recommendations.Add("检测到新设备，建议验证设备信息");

            if (factors.LocationConsistency < 0.3)
                recommendations.Add("检测到异常登录位置，建议确认身份");

            if (factors.TimePattern < 0.3)
                recommendations.Add("检测到异常登录时间，建议确认操作");

            if (factors.LoginFrequency < 0.3)
                recommendations.Add("检测到异常登录频率，建议检查账户安全");

            if (factors.BehaviorPattern < 0.3)
                recommendations.Add("检测到异常行为模式，建议进一步验证");

            if (recommendations.Count == 0)
                recommendations.Add("登录安全性良好");

            return recommendations;
        }
    }
}
